module App
    class Ktoggl
        attr_reader :settings, :tree, :watchdog, :ignored_clients

        def initialize()
            @settings = Qt::Settings.new("Magex", "Ktoggl")

            toggl = App::Toggl.new
            @tree = App::TogglTreeModel.new(toggl)
            @ignored_clients = App::IgnoredClientModel.new(self.get_ignored_clients)
            @watchdog = App::Watchdog.new(@tree)

            reload_settings
        end

        def reload_settings
            get_login
            get_toggl_settings
            # XXX emit signal
            $widget.dropwindow.view.tv.set_style if $widget
        end

        def store_login
            save_setting "email", @tree.toggl.email
            save_setting "password", @tree.toggl.password
        end

        def get_login
            @tree.toggl.email = load_setting("email").toString
            @tree.toggl.password = load_setting("password").toString
        end
        
        def store_ignored_clients(list)
            save_setting("ignored_clients", list)
        end

        def get_ignored_clients
            clients = load_setting("ignored_clients")
            if clients.type == Qt::Variant::String
                ret = [clients.toString]
            else
                ret = clients.toList.map{|qvar| qvar.to_string}
            end
            ret
        end

        def get_toggl_settings
            @tree.toggl.hide_older_than = load_setting("hide_older_than").toInt
            @tree.toggl.hide_older_than = 7 if @tree.toggl.hide_older_than == 0
        end

        def dropwin_style
            style = load_setting("dropwin_style").toString
            # It's an example, pretty ugly here.
            style ||= <<EOF
QTreeView {
  font: normal 10px;
  background: #15689F;
  alternate-background-color: #136194;
}
QTreeView::item:selected {
  color: white;
  border: 1px solid white;
  background: #1BA5CB;
}
EOF
            style
        end

        def dropwin_style=(text)
            save_setting "dropwin_style", text
        end

        def save_setting(key, value)
            @settings.beginGroup "Ktoggl"
            @settings.set_value key, Qt::Variant.new(value)
            @settings.endGroup
            @settings.sync
        end

        def load_setting(key)
            @settings.beginGroup "Ktoggl"
            ret = @settings.value key
            @settings.endGroup
            ret
        end
    end
end
